# -*-coding:Utf-8 -* 
""" SZ load module
"""
import bge, bgl, blf, mathutils, aud, os, pickle, types, threading
from .. import SZ_Globals,setState,exitgame, inputs as IN,gui as UI, common as core
from .parser import *
from .item import *
from .level import *

AUTORELOAD = True

from .modloader import *

def init_main_scene(evt,*args):
	""" Scenes initialization function """
	for scene in bge.logic.getSceneList():
		if scene.name in ('skybox','main'):
			scene.suspend()
			SZ_Globals[{'skybox':'SkyScene','main':'LvlScene'}[scene.name]] = scene
	
def gui_init(cont):
	scene = bge.logic.getCurrentScene()
	scene.post_draw.append(SZ_Globals['2DScreen'].draw)
	SZ_Globals['2DScreen'].setLayer('loading')
	
def init_game(cont):
	""" Game initialization function """
	obj = cont.owner
	SZ_Globals['MainObject'] = obj
	scene = bge.logic.getCurrentScene()
	SZ_Globals['MainScene'] = scene
	SZ_Globals['MainInputMap'].activate()
	bge.logic.addScene('skybox')
	bge.logic.addScene('main')
	bge.logic.addScene('gui')
	evt = core.Event(init_main_scene).delayEvent(0.5)
	evt.layer = 'lvl'
	evt.activate()
	obj['init_thread'] = modLoader(SZ_Globals['main_mod'])
	#setState("MainMenu")
	
def run_default(cont = None):
	""" Main game loop function """
	IN.MouseTracking.update(cont.sensors["Mouse"])
	SZ_Globals['2DScreen'].update_mouse(
		round(IN.MouseTracking.virtual_mouse.x*bge.render.getWindowWidth()),
		round((1.0-IN.MouseTracking.virtual_mouse.y)*bge.render.getWindowHeight()),
		cont.sensors["Mouse"])
	IN.JoystickControl.update(bge.logic.joysticks)
	mEvt = SZ_Globals["mEvent"]
	mEvt.__EV_Start__()

def run_init(cont):
	""" Game loop function used during the loading of the game """
	obj = cont.owner
	if 'structure' in obj:
		obj['structure']
		prog = obj['structure'].initMods(obj['cursor'],SZ_Globals)
		SZ_Globals['2DScreen'].setLayer('loading')
		SZ_Globals['loading'][1].level = (prog*0.7)+0.1
		if prog == 1.0:
			obj['structure'].loadItems()
			Level.globalLib = obj['structure'].getLibs()
			Level().levels = obj['structure'].loadMaps()
			SZ_Globals['core_func']['run'] = run_default
			SZ_Globals['PATH'] = '//'
			del SZ_Globals['MOD_ID']
			print('error script list :',obj['structure'].getErrorScripts())
			SZ_Globals['loading'][1].level = 1.0
			SZ_Globals['2DScreen'].setLayer()
			setState(obj['structure'].getState())
			return
		obj['cursor'] += 1
		return
	if 'init_thread' in obj and not obj['init_thread'].is_alive():
		obj['structure'] = obj['init_thread']
		obj['cursor'] = 0
		SZ_Globals['loading'][1].level = 0.1
		del obj['init_thread']
		if not obj['structure']:
			SZ_Globals['core_func']['run'] = run_default
			return
		keymap = obj['structure'].structure['keymap']
		del obj['structure'].structure['keymap']
		SZ_Globals['keymap'] = keymap
		
def run_wait_start(cont):
	if 'LvlScene' in SZ_Globals:
		SZ_Globals['MainObject']['init_thread'].start()
		SZ_Globals['MainObject']['init_thread'].join(30.0)
		SZ_Globals['core_func']['run'] = run_init
	
def run_ingame(cont = None):
	""" Light game loop function """
	mEvt = SZ_Globals["mEvent"]
	mEvt.__EV_Start__()
	
def run_quit(cont = None):
	""" Game loop function waiting until the game quit """
	return
	
def run_lvl(cont = None):
	""" In-game loop function executed in scene "main" """
	#IN.MouseTracking.update(cont.sensors["Mouse"])
	mEvt = SZ_Globals['lvl_mEvent']
	mEvt.__EV_Start__()
	
def exit_game(cont = None):
	""" Main exit function """
	if 'MainMenuMusic' in SZ_Globals:
		SZ_Globals['MainMenuMusic'][0].stop()
	SZ_Globals['MainScene'].post_draw.clear()
	UI.Image.freeAllTex()
	UI.Font.freeAllFonts()
	SZ_Globals['core_func']['run'] = run_quit
	SZ_Globals['core_func']['run_lvl'] = run_quit
	SZ_Globals['state'] = -1
	bge.logic.endGame()
